﻿using System;
using System.Data;
using System.Data.Common;
using System.Transactions;
using System.Xml.XPath;
using Songhay.Data.GenericWeb.Properties;
using Songhay.Xml;

namespace Songhay.Data.GenericWeb.Procedure
{
    /// <summary>
    /// Delete procedures for Web-schema data.
    /// </summary>
    internal static partial class Delete
    {
        internal static XPathDocument Segment(DbConnection commonConnection, IXPathNavigable navigableInput)
        {
            if(commonConnection == null) throw new ArgumentNullException("commonConnection", "The Common Connection is null.");

            XPathNavigator node = XmlUtility.GetNavigableNode(navigableInput, "//FormData");
            Object p = XmlUtility.GetNodeValue(node, "./SegmentId", true, DBNull.Value);

            string id = p.ToString();
            XPathDocument d = null;

            using(TransactionScope tscope = new TransactionScope())
            {
                using(DbCommand cmd = commonConnection.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = Resources.DeleteSegment;

                    DbParameter parameter;

                    parameter = cmd.CreateParameter();
                    parameter.ParameterName = "@SegmentId";
                    parameter.Value = id;
                    cmd.Parameters.Add(parameter);

                    cmd.ExecuteNonQuery();
                }

                using(DbCommand cmd = commonConnection.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = Resources.DeleteSegmentDocument;

                    DbParameter parameter;

                    parameter = cmd.CreateParameter();
                    parameter.ParameterName = "@DocumentId";
                    parameter.Value = DBNull.Value;
                    cmd.Parameters.Add(parameter);

                    parameter = cmd.CreateParameter();
                    parameter.ParameterName = "@SegmentId";
                    parameter.Value = id;
                    cmd.Parameters.Add(parameter);

                    cmd.ExecuteNonQuery();
                }

                tscope.Complete();

                string[] sa = new string[] { string.Format("Segment {0} has been removed.", id) };
                d = XmlUtility.GetInternalMessageDocument("Item Deleted from the Database", sa);
            }

            return d;
        }
    }
}
